package com.block.channelext.service.channel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.channelext.model.result.ReportResult;
import com.block.channelext.service.IChannelHandleService;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelInfo;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TuiAFlowChannelHandleService implements IChannelHandleService {

    private String requestUrl = "https://activity.tuia.cn/log/effect/v2";
    private String secretKey = "0CC7D958AABC4A691B5EC03BFF562B11";

    private static Logger log = LogFactory.getCommLog();

    @Override
    public ReportResult registerAction(ChannelInfo channelInfo, JSONObject extJson) {

        String aOId = extJson.getString("aOId");
        if (StrUtil.isEmpty(aOId)){
            return ReportResult.newInstance();
        }

        String reqIp = extJson.getString("reqIp");

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("a_oId", aOId);
        bizMap.put("advertKey", secretKey);
        bizMap.put("subType", "3");
        bizMap.put("ip", reqIp);

        log.info("【推啊信息流上报】【注册】【开始请求】【reqestUrl】{}【bizMap】{}", requestUrl, JSON.toJSONString(bizMap));
        String response = HttpUtil.createPost(requestUrl)
                .form(bizMap)
                .execute().body();
        log.info("【推啊信息流上报】【注册】【开始结束】【result】{}", response);

        ReportResult reportResult = ReportResult.newInstance(JSON.toJSONString(bizMap), response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String code = jsonObject.getString("record");
        String message = jsonObject.getString("redesc");
        reportResult.setCode(code);
        reportResult.setMessage(message);
        if (StrUtil.equals(code, "0000000")){
            reportResult.setSuccess(true);
        }

        return reportResult;
    }

    @Override
    public ReportResult authAction(ChannelInfo channelInfo, JSONObject extJson) {

        return ReportResult.newInstance();
    }

    @Override
    public ReportResult proUvAction(ChannelInfo channelInfo, JSONObject extJson) {

        return ReportResult.newInstance();
    }

}
